package com.movieproject.daos.imp;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.movieproject.daos.OrderDAO;
import com.movieproject.dataobjects.Movie;
import com.movieproject.dataobjects.Order;
import com.movieproject.dataobjects.User;

@Service
public class OrderDAOImp implements OrderDAO {
    
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<Order> getAllOrders() {
		Query query = sessionFactory.getCurrentSession().createQuery("from Order");
		List<?> l = query.list(); // query returns a raw list. 
		ArrayList<Order> orderList = new ArrayList<Order>();
		for(Object o : l) {	// objects in list must be cast individually
		    orderList.add((Order) o);
		}
		return orderList;
    }

    @Override
    public List<Order> getOrdersByMovie(Movie movie) {
		Query query = sessionFactory.getCurrentSession().createQuery("from Order where MovieID = :m");
		query.setParameter("m", movie.getMovieID());
		List<?> l = query.list(); // query returns a raw list. 
		ArrayList<Order> orderList = new ArrayList<Order>();
		for(Object o : l) {	// objects in list must be cast individually
		    orderList.add((Order) o);
		}
		return orderList;
    }

    @Override
    public List<Order> getOrdersByUser(User user) {
		Query query = sessionFactory.getCurrentSession().createQuery("from Order where UserID = :u");
		query.setParameter("u", user.getUserID());
		List<?> l = query.list(); // query returns a raw list. 
		ArrayList<Order> orderList = new ArrayList<Order>();
		for(Object o : l) {	// objects in list must be cast individually
		    orderList.add((Order) o);
		}
		return orderList;
    }
    
    public List<Order> getOrdersCheckedOut()	{
	    Query query = sessionFactory.getCurrentSession().createQuery("from Order where returned = 0");
		List<?> l = query.list(); // query returns a raw list. 
		ArrayList<Order> orderList = new ArrayList<Order>();
		for(Object o : l) {	// objects in list must be cast individually
		    orderList.add((Order) o);
		}
		return orderList;
    }

    @Override
    public Order getOrder(int orderID) {
		return (Order) sessionFactory.getCurrentSession().get(Order.class, orderID);
    }

    @Override
    public void updateOrder(Order order) {
		sessionFactory.getCurrentSession().merge(order);
    }

    @Override
    public void deleteOrder(Order order) {
		sessionFactory.getCurrentSession().delete(order);
    }
}
